import { initTRPC } from '@trpc/server';
import { createSuccessResponse } from '../utils/response';
import type { TRPCContext } from './context';
import { z } from 'zod';
import { ManagerService } from '../services/managerService';
import { ServiceService } from '../services/serviceService';
import { ImportService } from '../services/importService';
import { StatsService } from '../services/statsService';
import { WorkLogService } from '../services/workLogService';
import { ReminderService } from '../services/reminderService';
import { AuthService } from '../services/authService';
import { ClientService } from '../services/clientService';
import { CleanupService } from '../services/cleanupService';
import { TimerService } from '../services/timerService';
import { CompletionCycle, MarketType, TerminalType } from '@prisma/client';

const t = initTRPC.context<TRPCContext>().create();

export const router = t.router;
export const publicProcedure = t.procedure;

// 健康检查路由
const healthRouter = router({
  check: publicProcedure
    .query(() => {
      return createSuccessResponse({
        status: 'ok',
        timestamp: new Date().toISOString(),
        service: 'vue-turbo-stack-api',
        version: '1.0.0',
        uptime: process.uptime(),
      }, '服务运行正常');
    }),
});

// 客户经理管理路由
const managerRouter = router({
  create: publicProcedure
    .input(z.object({
      username: z.string().min(3).max(50),
      password: z.string().min(6).max(100),
      fullName: z.string().min(1).max(50),
    }))
    .mutation(async ({ input }) => {
      return await ManagerService.createManager(input);
    }),

  update: publicProcedure
    .input(z.object({
      id: z.number().int().positive(),
      username: z.string().min(3).max(50).optional(),
      password: z.string().min(6).max(100).optional(),
      fullName: z.string().min(1).max(50).optional(),
    }))
    .mutation(async ({ input }) => {
      return await ManagerService.updateManager(input);
    }),

  delete: publicProcedure
    .input(z.object({
      id: z.number().int().positive(),
    }))
    .mutation(async ({ input }) => {
      return await ManagerService.deleteManager(input);
    }),

  get: publicProcedure
    .input(z.object({
      id: z.number().int().positive(),
    }))
    .query(async ({ input }) => {
      return await ManagerService.getManager(input);
    }),

  list: publicProcedure
    .input(z.object({
      page: z.number().int().positive().default(1),
      pageSize: z.number().int().positive().max(100).default(10),
      search: z.string().optional(),
    }))
    .query(async ({ input }) => {
      return await ManagerService.listManagers(input);
    }),

  clients: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      page: z.number().int().positive().default(1),
      pageSize: z.number().int().positive().max(100).default(10),
      search: z.string().optional(),
    }))
    .query(async ({ input }) => {
      return await ManagerService.getManagerClients(input);
    }),
});

// 服务项目管理路由
const serviceRouter = router({
  create: publicProcedure
    .input(z.object({
      serviceName: z.string().min(1).max(100),
      completionCycle: z.nativeEnum(CompletionCycle),
      cycleValue: z.number().int().positive().max(255).default(1),
      startDate: z.string().datetime().optional(),
      endDate: z.string().datetime().optional(),
      reminderFrequency: z.string().max(50).optional(),
      reminderContent: z.string().optional(),
    }))
    .mutation(async ({ input }) => {
      return await ServiceService.createService(input);
    }),

  update: publicProcedure
    .input(z.object({
      id: z.number().int().positive(),
      serviceName: z.string().min(1).max(100).optional(),
      completionCycle: z.nativeEnum(CompletionCycle).optional(),
      cycleValue: z.number().int().positive().max(255).optional(),
      startDate: z.string().datetime().optional(),
      endDate: z.string().datetime().optional(),
      reminderFrequency: z.string().max(50).optional(),
      reminderContent: z.string().optional(),
    }))
    .mutation(async ({ input }) => {
      return await ServiceService.updateService(input);
    }),

  delete: publicProcedure
    .input(z.object({
      id: z.number().int().positive(),
    }))
    .mutation(async ({ input }) => {
      return await ServiceService.deleteService(input);
    }),

  get: publicProcedure
    .input(z.object({
      id: z.number().int().positive(),
    }))
    .query(async ({ input }) => {
      return await ServiceService.getService(input);
    }),

  list: publicProcedure
    .input(z.object({
      page: z.number().int().positive().default(1),
      pageSize: z.number().int().positive().max(100).default(10),
      search: z.string().optional(),
    }))
    .query(async ({ input }) => {
      return await ServiceService.listServices(input);
    }),
});

// 客户管理路由
const clientRouter = router({
  create: publicProcedure
    .input(z.object({
      clientCode: z.string().min(1).max(12),
      clientName: z.string().min(1).max(100),
      marketType: z.nativeEnum(MarketType),
      terminalType: z.nativeEnum(TerminalType),
    }))
    .mutation(async ({ input }) => {
      return await ClientService.createClient(input);
    }),

  update: publicProcedure
    .input(z.object({
      id: z.number().int().positive(),
      clientCode: z.string().min(1).max(12).optional(),
      clientName: z.string().min(1).max(100).optional(),
      marketType: z.nativeEnum(MarketType).optional(),
      terminalType: z.nativeEnum(TerminalType).optional(),
    }))
    .mutation(async ({ input }) => {
      return await ClientService.updateClient(input);
    }),

  delete: publicProcedure
    .input(z.object({
      id: z.number().int().positive(),
    }))
    .mutation(async ({ input }) => {
      return await ClientService.deleteClient(input);
    }),

  get: publicProcedure
    .input(z.object({
      id: z.number().int().positive(),
    }))
    .query(async ({ input }) => {
      return await ClientService.getClient(input);
    }),

  list: publicProcedure
    .input(z.object({
      page: z.number().int().positive().default(1),
      pageSize: z.number().int().positive().max(100).default(10),
      search: z.string().optional(),
    }))
    .query(async ({ input }) => {
      return await ClientService.listClients(input);
    }),

  assignManager: publicProcedure
    .input(z.object({
      clientId: z.number().int().positive(),
      managerId: z.number().int().positive(),
    }))
    .mutation(async ({ input }) => {
      return await ClientService.assignManager(input);
    }),

  unassignManager: publicProcedure
    .input(z.object({
      clientId: z.number().int().positive(),
      managerId: z.number().int().positive(),
    }))
    .mutation(async ({ input }) => {
      return await ClientService.unassignManager(input);
    }),

  managerUpdate: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      clientId: z.number().int().positive(),
      clientName: z.string().min(1).max(100).optional(),
      marketType: z.nativeEnum(MarketType).optional(),
      terminalType: z.nativeEnum(TerminalType).optional(),
    }))
    .mutation(async ({ input }) => {
      return await ClientService.managerUpdateClient(input);
    }),
});

// 数据导入路由
const importRouter = router({
  getOptions: publicProcedure
    .input(z.object({
      search: z.string().optional(),
    }))
    .query(async ({ input }) => {
      return await ImportService.getImportOptions(input);
    }),

  preview: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      serviceIds: z.array(z.number().int().positive()).min(1),
      clients: z.array(z.object({
        clientCode: z.string().min(1).max(12),
        clientName: z.string().min(1).max(100),
        marketType: z.nativeEnum(MarketType),
        terminalType: z.nativeEnum(TerminalType),
      })).min(1),
    }))
    .mutation(async ({ input }) => {
      return await ImportService.previewImport(input);
    }),

  import: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      serviceIds: z.array(z.number().int().positive()).min(1),
      clients: z.array(z.object({
        clientCode: z.string().min(1).max(12),
        clientName: z.string().min(1).max(100),
        marketType: z.nativeEnum(MarketType),
        terminalType: z.nativeEnum(TerminalType),
      })).min(1),
    }))
    .mutation(async ({ input }) => {
      return await ImportService.importClients(input);
    }),
});

// 统计数据路由
const statsRouter = router({
  dashboard: publicProcedure
    .input(z.object({
      startDate: z.string().optional(),
      endDate: z.string().optional(),
    }))
    .query(async ({ input }) => {
      return await StatsService.getDashboardStats(input);
    }),

  managerDetails: publicProcedure
    .input(z.object({
      startDate: z.string().optional(),
      endDate: z.string().optional(),
    }))
    .query(async ({ input }) => {
      return await StatsService.getManagerDetails(input);
    }),

  serviceDetails: publicProcedure
    .input(z.object({
      startDate: z.string().optional(),
      endDate: z.string().optional(),
    }))
    .query(async ({ input }) => {
      return await StatsService.getServiceDetails(input);
    }),

  managerDetail: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      startDate: z.string().optional(),
      endDate: z.string().optional(),
    }))
    .query(async ({ input }) => {
      return await StatsService.getManagerDetail(input);
    }),

  serviceDetail: publicProcedure
    .input(z.object({
      serviceId: z.number().int().positive(),
      startDate: z.string().optional(),
      endDate: z.string().optional(),
    }))
    .query(async ({ input }) => {
      return await StatsService.getServiceDetail(input);
    }),

  detailed: publicProcedure
    .input(z.object({
      startDate: z.string().optional(),
      endDate: z.string().optional(),
    }))
    .query(async ({ input }) => {
      return await StatsService.getDetailedStats(input);
    }),
});

// 工作日志路由
const workLogRouter = router({
  create: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      clientId: z.number().int().positive(),
      serviceId: z.number().int().positive(),
      completionDate: z.string().datetime(),
      notes: z.string().optional(),
    }))
    .mutation(async ({ input }) => {
      return await WorkLogService.createWorkLog(input);
    }),

  list: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      startDate: z.string().datetime().optional(),
      endDate: z.string().datetime().optional(),
      serviceId: z.number().int().positive().optional(),
      page: z.number().int().positive().default(1),
      pageSize: z.number().int().positive().max(100).default(20),
    }))
    .query(async ({ input }) => {
      return await WorkLogService.getWorkLogs(input);
    }),

  byDate: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      date: z.string().datetime(),
    }))
    .query(async ({ input }) => {
      return await WorkLogService.getWorkLogsByDate(input);
    }),

  delete: publicProcedure
    .input(z.object({
      id: z.string(),
      managerId: z.number().int().positive(),
    }))
    .mutation(async ({ input }) => {
      return await WorkLogService.deleteWorkLog(input);
    }),

  serviceStats: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      serviceId: z.number().int().positive(),
      startDate: z.string().datetime().optional(),
      endDate: z.string().datetime().optional(),
    }))
    .query(async ({ input }) => {
      return await WorkLogService.getServiceStats(input);
    }),

  searchClients: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      keyword: z.string().min(1),
      serviceId: z.number().int().positive().optional(),
    }))
    .query(async ({ input }) => {
      return await WorkLogService.searchClients(input);
    }),
});

// 任务提醒路由
const reminderRouter = router({
  // 新的合并接口：获取完整任务数据
  dashboard: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      includeProgressComparison: z.boolean().default(false),
    }))
    .query(async ({ input }) => {
      return await ReminderService.getTaskDashboard(input);
    }),

  list: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
    }))
    .query(async ({ input }) => {
      return await ReminderService.getReminders(input);
    }),

  serviceProgress: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      serviceId: z.number().int().positive(),
    }))
    .query(async ({ input }) => {
      return await ReminderService.getServiceProgress(input);
    }),

  getSettings: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
    }))
    .query(async ({ input }) => {
      return await ReminderService.getReminderSettings(input);
    }),

  saveSettings: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      weeklyReminder: z.boolean(),
      deadlineReminder: z.boolean(),
      reminderTime: z.string().regex(/^\d{2}:\d{2}$/),
    }))
    .mutation(async ({ input }) => {
      return await ReminderService.saveReminderSettings(input);
    }),

  progressComparison: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      serviceId: z.number().int().positive(),
    }))
    .query(async ({ input }) => {
      return await ReminderService.getProgressComparison(input);
    }),
});

// 清理路由
const cleanupRouter = router({
  // 手动触发清理无人维护的客户
  cleanUnmanagedClients: publicProcedure
    .mutation(async () => {
      return await CleanupService.cleanupUnmanagedClients();
    }),

  // 获取无人维护的客户统计信息
  getUnmanagedClientsStats: publicProcedure
    .query(async () => {
      return await CleanupService.getUnmanagedClientsStats();
    }),

  // 获取定时器状态
  getTimerStatus: publicProcedure
    .query(async () => {
      return TimerService.getTimerStatus();
    }),

  // 重启客户清理定时器
  restartCleanupTimer: publicProcedure
    .mutation(async () => {
      TimerService.restartCleanupTimer();
      return { success: true, message: '客户清理定时器已重启' };
    }),
});

// 认证路由
const authRouter = router({
  managerLogin: publicProcedure
    .input(z.object({
      username: z.string().min(3).max(50),
      password: z.string().min(6).max(100),
    }))
    .mutation(async ({ input }) => {
      return await AuthService.managerLogin(input);
    }),

  verifyToken: publicProcedure
    .input(z.object({
      token: z.string(),
    }))
    .query(async ({ input }) => {
      return await AuthService.verifyManagerToken(input.token);
    }),

  profile: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
    }))
    .query(async ({ input }) => {
      return await AuthService.getManagerProfile(input.managerId);
    }),

  changePassword: publicProcedure
    .input(z.object({
      managerId: z.number().int().positive(),
      oldPassword: z.string().min(6).max(100),
      newPassword: z.string().min(6).max(100),
    }))
    .mutation(async ({ input }) => {
      return await AuthService.changePassword(input);
    }),
});

// 主路由
export const appRouter = router({
  health: healthRouter,
  manager: managerRouter,
  service: serviceRouter,
  client: clientRouter,
  import: importRouter,
  stats: statsRouter,
  workLog: workLogRouter,
  reminder: reminderRouter,
  auth: authRouter,
  cleanup: cleanupRouter,
});

export type AppRouter = typeof appRouter;
